import React, { Component } from 'react'
import { Tabs, Button, Modal, Form, Card, Row, Col, Icon, Upload } from 'antd';
import * as APIService from '../../axios/api_yq'
import { withRouter } from "react-router-dom";
import { BasicLayout, BasicLayoutSearch } from '../../components/BasicLayout';
import { BasicPagination, TableCustomize, openSuccessModal, openModalMessage } from '../../components/TableCustomize';
import SearchForm from './SearchForm';
import SearchForms from './SearchForms'
import AddForm from './AddForm';
import AddForm1 from './AddForm1';
import { baseUrl } from '../../config';
const { TabPane } = Tabs;
const { confirm } = Modal;
const FormItem = Form.Item;
const formItemLayout = {
    // 抽屉里面Form。二列的布局比例
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 18
    }
};
class App extends Component {
    state = {
        visible: false,
        modalTitle: '新增',
        one: false,
        reportData: [],
        formData: {},
        loading: false,
        dataSource: [],
        editData: {},
        visible1: false,
        visible2: false,
        visible3: false,
        datas: {},
        tabKey: 1,
        randomKey: 0,//随机数
        uploadData: [],
        paging: {}
    }
    // 挂载前
    UNSAFE_componentWillMount() {
        this.getReportList()
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    // 初次渲染 (查看看板界面配置带分页)
    fetch = (pageNum = 1, pageSize = 100) => {
        let data = 'pageNum=' + pageNum + '&pageSize=' + pageSize
        this.setState({
            paging: { pageNum: pageNum, pageSize: pageSize }
        })
        this.queryBoardViewConfig(data)
    }
    //查看看板配置 queryBoardConfig
    getReportList = data => {
        APIService.queryBoardConfig(data).then(item => {
            console.log('查看看板配置', item);
            if (item.data.data.code === 200) {
                this.setState({
                    reportData: item.data.data.data
                })
            } else {
                openModalMessage('error', item.data.data.msg)
            }
        })
    }
    // 屏幕名称查询 
    handleSearch = value => {
        console.log(value);
        let data = ''
        if (value.screenName) {
            data += 'screenName=' + value.screenName
        }
        this.getReportList(data)
    };
    //tab切换
    tabChange = key => {
        console.log(key)
        if (parseInt(key) === 1) {
            this.getReportList()
        }
        if (parseInt(key) === 2) {
            this.fetch()
        }
        this.setState({
            tabKey: parseInt(key)
        })
    }
    // 新增、设置
    showModal = (a, b) => {
        console.log(a, b);
        if (b === 1) {
            this.setState({
                visible: true,
                one: true,
                modalTitle: '设置',
                formData: a
            });
        } else {
            this.setState({
                visible: true,
                one: false,
                modalTitle: '新建'
            });
        }
    }
    // 确定
    showModal1 = () => {
        const { formData } = this.state
        let id = formData.id
        this.formDrawer.validateFields((err, value) => {
            console.log(value);
            let a = { ...value, id }
            APIService.saveOrUpdateBoardConfig(a).then((item) => {
                if (item.data.code === 200) {
                    openSuccessModal(item.data.msg)
                    this.handleCancel()
                    this.getReportList()
                } else {
                    openModalMessage('error', item.data.msg)
                }
                console.log('新增/修改看板配置', item);
            })
            if (err) return;
        })
    }
    // 取消
    handleCancel = e => {            //表单重置函数
        this.formAdd && this.formAdd.resetFields();
        this.setState({
            visible: false,
            one: false,
            visible1: false,
            visible2: false,
            visible3: false,
        });
    };
    // 暂停
    startStop = (item, b) => {
        // console.log(item, b);
        let status = item.status = 0
        let a = { ...item, status }
        APIService.saveOrUpdateBoardConfig(a).then((item) => {
            if (item.data.code === 200) {
                openSuccessModal(item.data.msg)
                this.getReportList()
            } else {
                openModalMessage('error', item.data.msg)
            }
            console.log('新增/修改看板配置', item);
        })
    }
    // 启用
    startStop1 = (item) => {
        let id = 'id=' + item.id
        APIService.startBoard(id).then((item) => {
            console.log(item);
            this.getReportList()
        })
        console.log(1);
    }
    // 删除
    delete = (value) => {
        let that = this
        confirm({
            title: '确定要删除吗?',
            onOk() {
                let data = ''
                if (value.id) {
                    data += 'ids=' + value.id
                }
                APIService.deleteBoardConfig(data).then((item) => {
                    if (item.data.code === 200) {
                        openSuccessModal(item.data.msg)
                        that.getReportList()
                    } else {
                        openModalMessage('error', item.data.msg)
                    }
                })
            },
            onCancel() {
                openModalMessage('warning', '已取消')
            },
        });

    }


    // 报表配置____________________________________________
    // 姓名搜索
    handleSearchs = (value) => {
        console.log('姓名搜索', value);
        let data = 'reportViewName=' + value.screenName
        console.log(data);
        this.queryBoardViewConfig(data)
    }
    // 查看看板界面配置带分页
    queryBoardViewConfig = (data) => {
        APIService.queryBoardViewConfig(data).then((item) => {
            if (item.data.data.code === 200) {
                this.setState({
                    dataSource: item.data.data.data,
                    paging: {
                        pageNum: item.data.data.pageNum,
                        pageSize: item.data.data.pageSize,
                        total: item.data.data.total,
                    }
                })

            } else {
                openModalMessage('error', item.data.data.msg)
            }
            console.log('查看看板界面配置带分页', item);
        })
    }
    // 编辑
    showModalView = (data) => {
        console.log(data);
        if (data.typeId === 0) {
            this.setState({
                visible1: true,
                datas: data
            })
        }
        if (data.typeId === 1) {
            this.setState({
                visible2: true,
                randomKey: Math.random()
            })
        }
        if (data.typeId === 2) {
            this.setState({
                visible3: true
            })
        }
        this.setState({
            editData: data
        })
    }
    // 文字 确认
    showModal12 = () => {
        const { datas } = this.state
        this.formDrawer1.validateFields((err, value) => {
            console.log(value);
            let a = 'id=' + datas.id + '&word=' + value.content
            console.log(a);
            APIService.editWord(a).then((item) => {
                console.log(item);
                if (item.data.code === 200) {
                    openSuccessModal('修改成功')
                    this.queryBoardViewConfig()
                    this.setState({
                        visible1: false
                    })
                } else {
                    openModalMessage('error', '失败')
                }
            })
            if (err) return;
        })
    }
    // 图片
    showModal13 = () => {
        this.setState({
            visible2: false
        })
    }
    // 视频
    showModal14 = () => {
        this.setState({
            visible3: false
        })
    }
    render() {
        const that = this
        // 新增按钮
        var operations = <div className="mydiv" >
            {this.state.tabKey === 1 ? <Button icon="plus" onClick={() => this.showModal([], 0)} type="primary" > 新增 </Button> : null}</div >
        const { randomKey, paging, modalTitle, visible, one, reportData, formData, dataSource, loading, visible1, visible2, visible3 } = this.state
        const columns = [
            {
                dataIndex: '',
                width: 80
            },

            {
                title: '序号',
                width: 200,
                render: (text, record, index) => `${index + 1}`,
            },
            {
                title: '名称',
                dataIndex: 'name',
            },
            {
                title: '文件类型',
                dataIndex: 'typeId',
                render: (text, record) => {
                    if (text === 0) {
                        return <span>文字</span>
                    } if (text === 1) {
                        return <span>图片</span>
                    } if (text === 2) {
                        return <span>视频</span>
                    } if (text === 3) {
                        return <span>报表</span>
                    }
                }
            },
            {
                title: '操作',
                width: 200,
                render: (text, record) => {
                    return <span>
                        <a onClick={() => this.showModalView(record)}>编辑</a>
                    </span>
                }
            }
        ]

        const { getFieldDecorator } = this.props.form;
        //上传图片 视频
        const propsP = {
            name: 'file',
            showUploadList: true,
            // 修改上传地址
            action: baseUrl + '/boardcontent/uploadImage',
            headers: {
                Token: localStorage.getItem('token'),
            },
            multiple: true,
            onChange(info) {
                console.log('这是', info, info.file.status)
                if (info.file.status !== 'uploading') {
                    // console.log('123123', info.file, info.fileList);
                }
                // 成功
                if (info.file.status === 'done') {
                    if (info.file.response.data) {
                        // that.setState({
                        //     uploadData: info.file.response.data
                        // }, () => { console.log('这是', this.state.uploadData); })
                        console.log('成功回调', info.file.response.data);
                        openSuccessModal('上传成功')
                    }
                } else if (info.file.status === 'error') {
                    openModalMessage('error', '失败')
                }
            },
        };
        return (
            <div>
                <BasicLayoutSearch>
                    {/*      新增按钮 */}
                    <Tabs tabBarExtraContent={operations} onChange={this.tabChange}>
                        <TabPane tab="车间大屏控制" key="1">
                            <SearchForm onSearch={this.handleSearch} />
                            <div className="rightCenterBody" style={{ flexWrap: 'wrap', display: 'flex', paddingLeft: 20 }}>
                                {
                                    reportData.map(item => {
                                        return <Card key={item.id} title={item.screenName} extra={<div>
                                            {item.status === 0 ? <Button type='primary' style={{ backgroundColor: '#D9011B', border: 'none' }} onClick={() => { this.startStop(item, 0) }}>暂停</Button> :
                                                <Button type='primary' style={{ backgroundColor: '#95F204', border: 'none' }} onClick={() => { this.startStop1(item, 1) }}>启用</Button>}
                                            &nbsp;<Button onClick={() => { this.showModal(item, 1) }}>设置</Button>&nbsp;<Button onClick={() => { this.delete(item) }}>删除</Button>
                                        </div>} style={{ width: 400, marginLeft: 50, marginTop: 5 }}>
                                            <Row style={{ width: '100%', height: '350px', border: '1px solid #ccc', paddingTop: '130px' }}>
                                                {/* display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center'  */}
                                                <Col span={14} offset={6}><span style={{ fontWeight: 'bold' }}>屏幕名称：</span> {item.screenName}</Col>

                                                <Col span={14} offset={6}> <span style={{ fontWeight: 'bold' }}>终端地址：</span>  {item.equId}</Col>
                                                <Col span={14} offset={6}><span style={{ fontWeight: 'bold' }}>播放形式：</span>{item.typeId === 0 ? '固定页面' : '循环播放'}</Col>
                                                {
                                                    item.typeId === 1 ? <Col span={14} offset={6}> <span style={{ fontWeight: 'bold' }}>循环间隔：</span>{item.blankTime === 0 ? '10s' : item.blankTime === 1 ? '20s' : item.blankTime === 2 ? '30s' : item.blankTime === 3 ? '1min' : item.blankTime === 4 ? '10min' : ''}</Col> : null
                                                }
                                                <Col span={14} offset={6}> <span style={{ fontWeight: 'bold' }}>描述：</span>{item.describes}</Col>
                                            </Row>
                                            {/* <img width='100%' height='350px' /> */}
                                        </Card>
                                    })
                                }
                            </div>

                        </TabPane>
                        <TabPane tab="报表配置" key="2">
                            <SearchForms onSearch={this.handleSearchs} />
                            <BasicLayout name="检验标准" icon="table" >
                                <TableCustomize columns={columns} rowKey={(record) => record.id} dataSource={dataSource} pagination={false} loading={loading} allowDrafting={true} />

                                <BasicPagination pageNum={paging.pageNum} pageSize={paging.pageSize} total={paging.total} loadData={this.fetch} >

                                </BasicPagination>
                            </BasicLayout>
                        </TabPane>
                    </Tabs>
                </BasicLayoutSearch>
                <Modal
                    visible={visible}
                    destroyOnClose
                    title={modalTitle}
                    onOk={this.showModal1}
                    onCancel={this.handleCancel}
                    okText="保存"
                    cancelText="取消"
                >
                    <AddForm
                        onOk={this.showModal1}
                        formData={formData}
                        ref={node => (this.formDrawer = node)}
                        one={one}
                    />
                </Modal>
                {/* 文字 */}
                <Modal
                    visible={visible1}
                    destroyOnClose
                    title={'编辑'}
                    onOk={this.showModal12}
                    onCancel={this.handleCancel}
                    okText="保存"
                    cancelText="取消"
                >
                    <AddForm1
                        onOk={this.showModal12}
                        formData={formData}
                        ref={node => (this.formDrawer1 = node)}
                        one={one}
                    />
                </Modal>
                {/* 图片 */}
                <Modal
                    visible={visible2}
                    destroyOnClose
                    title={'编辑'}
                    onOk={this.showModal13}
                    onCancel={this.handleCancel}
                    okText="保存"
                    cancelText="取消"
                >
                    <Form >
                        <Row>
                            <Col span={24}>
                                <FormItem {...formItemLayout} label={'配置图片源:'}>
                                    {getFieldDecorator('name', {
                                        rules: [{ required: true, message: '请输入配置图片源！' }]
                                    })(
                                        // <Input />
                                        <div key={randomKey}>
                                            <Upload
                                                {...propsP}
                                            >
                                                <Button>
                                                    <Icon type="upload" /> 选择图片
                                                </Button>
                                            </Upload>
                                        </div>
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
                {/* 视频 */}
                <Modal
                    visible={visible3}
                    destroyOnClose
                    title={'编辑'}
                    onOk={this.showModal14}
                    onCancel={this.handleCancel}
                    okText="保存"
                    cancelText="取消"
                >
                    <Form >
                        <Row>
                            <Col span={24}>
                                <FormItem {...formItemLayout} label={'配置视频源:'}>
                                    {getFieldDecorator('name', {
                                        rules: [{ required: true, message: '请输入配置视频源！' }]
                                    })(
                                        <div key={randomKey}>
                                            <Upload
                                                {...propsP}
                                            >
                                                <Button>
                                                    <Icon type="upload" /> 选择视频
                                                </Button>
                                            </Upload>
                                        </div>
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Modal>

            </div>
        )
    }
}
export default Form.create()(withRouter(App));